package com.genesis.mall.service.impl;

import com.genesis.mall.dto.UmsMenuDto;
import com.genesis.mall.entity.UmsMenu;
import com.genesis.mall.mapper.UmsMenuMapper;
import com.genesis.mall.service.IUmsMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Service
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements IUmsMenuService {

    @Autowired
    private UmsMenuMapper umsMenuMapper;

    @Override
    public List<UmsMenuDto> getTreeList() {
        //获取所有启动的菜单列表
        List<UmsMenuDto> umsMenus = umsMenuMapper.findAll();
        //获得所有的根节点
        List<UmsMenuDto> rootMenu = umsMenus.stream().filter(menu -> menu.getLevel() == 0).collect(Collectors.toList());
        List<UmsMenuDto> dtoList = rootMenu.stream().map(menu -> {
            List<UmsMenuDto> child = getChild(menu.getId(), umsMenus);
            menu.setChildren(child);
            return menu;
        }).collect(Collectors.toList());
        return dtoList;
    }

    private List<UmsMenuDto> getChild(Long id, List<UmsMenuDto> umsMenus) {
        List<UmsMenuDto> childList = umsMenus.stream().filter(menu ->
                Objects.equals(menu.getParentId(), id)
        ).collect(Collectors.toList());

        for (UmsMenuDto umsMenuDto : childList) {
            umsMenuDto.setChildren(getChild(umsMenuDto.getId(),umsMenus));
        }
        if (childList.size()==0){
            return new ArrayList<>();
        }
        return childList;
    }
}
